import 'dart:async';
import 'package:lax/middlewares/cros.dart';

import 'config/Config.dart' as cnf;
import 'handler/Handler.dart' as handler;
import 'utils/LxServer.dart';
import 'package:args/args.dart';
import 'utils/MailSender.dart';

void main(List<String> args) {
  runZonedGuarded(() => myApp(args), Guarder().guard);
}

void myApp(List<String> args) {
  var parser = ArgParser()..addOption('env', defaultsTo: 'DEBUG');
  var results = parser.parse(args);
  cnf.env = results['env'];
  var server = LxServer(port: 9005, domain: '1.14.59.236');
  configRoute(server); //注册路由
  registeCronJob(server); //注册定时任务
  server.serve();
}

//路由配置
void configRoute(LxServer server) async {
  //使用中间件
  server.use(CROS);

  var root = server.getRouter();
  //  http://ip:port/
  root.get('', handler.HandleGetDefault);

  //DEMO
  {
    var demo = root.group('demo');
    // http://ip:port/demo/get
    demo.get('get', handler.HandleGetDefault);
    // http://ip:port/demo/post
    demo.post('post', handler.HandlePostDefault);
    // http://ip:port/demo/post
    demo.post('score', handler.HandleGetScores);
    // http://ip:port/demo/html
    demo.get('html', handler.HandleHtml);
  }
  return;
}

//注册定时任务
void registeCronJob(LxServer server) {
  server.registeCronJob(
      hour: 21,
      minute: 06,
      job: () {
        print('finish!!');
        return false;
      });
}

//异常处理类
class Guarder {
  DateTime lastSendTime = DateTime(2018);
  void guard(e, st) {
    // if (DateTime.now().difference(lastSendTime).inHours >= 1) {
    //   MailSender.sendMessage(
    //       targetMai: 'yourmail',
    //       title: '服务器出现异常',
    //       info: '服务器出现异常：</br>$e</br>$st');
    //   print(e);
    //   print(st);
    //   lastSendTime = DateTime.now();
    // }
    // print('${DateTime.now()}:  $e');
    // print('${DateTime.now()}:  $st');
    return;
  }
}
